package model;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;

public class FileOpener {
	private FileInputStream instream;
	private BufferedReader buff;
	
	public FileOpener(String filename){
		setInstream(filename);
	}
	
	public void setInstream(String filename) {
		try{
			instream= new FileInputStream(filename);
			buff= new BufferedReader(new InputStreamReader(instream));
		}
		catch(Exception e){
			System.out.println(e.getMessage());
		}
	}

	public int[][] Read() {
		String linea;
		char caracter;
		ArrayList<ArrayList<Integer>> Matriz = new ArrayList<ArrayList<Integer>>();
		ArrayList<Integer> fila = new ArrayList<Integer>();
		ArrayList<Integer>buffer= new ArrayList<Integer>();
		try{
		while((linea = buff.readLine()) != null){
			if(linea.contains("P")){
				int i=linea.indexOf(" ");
			for (;i<linea.length();i++){
				caracter=linea.charAt(i);
				boolean negativo=false;
				buffer.clear();
				int k=0;
			while((caracter>= '0' && caracter<='9') || caracter=='-'){
				if(caracter== '-'){
					negativo=true;
				}
				else{
				buffer.add(caracter-48);
				k++;
				}
				if (i<linea.length()-1){
					i++;
					caracter=linea.charAt(i);
				}
				else{
					caracter=' ';
				}
			}
				if(!buffer.isEmpty()){
					fila.add(toNumber(buffer,negativo));
				}
			}
			Matriz.add((ArrayList<Integer>) fila.clone());
			
			fila.clear();
		}
		
	}
		}
		catch(Exception e){}	
		for (int i=-1; i<Matriz.size();i++){
			for (int j=0; j<Matriz.get(0).size();j++){
				if (i==-1){
					System.out.printf("%3s" , "T"+j);
				}
				else{
				String s= ((Matriz.get(i).get(j).toString()));
				System.out.printf("%3s" , s);
				}
			}
			System.out.print("\n");
		}
		return ListToArray(Matriz);
	}
	 
	 public int[][] ListToArray( ArrayList<ArrayList<Integer>> l){
		 int[][]mAux = new int[l.size()][l.get(0).size()];
		 
		 for (int i=0; i<l.size();i++){
				for (int j=0; j<l.get(0).size();j++){
					mAux[i][j]=l.get(i).get(j);
					}
				}
		 
		 return mAux;
	 }
	 
	 public int toNumber(ArrayList<Integer> buffer,boolean signo){
	 int m= buffer.size();
	 int resultado=0;

	 for (int i=0; i<m;i++){
	 resultado=resultado + buffer.get(i)*(int) Math.pow(10, (m-1)-i);
	 }
	 if(signo){resultado=-resultado;}

	 return resultado;
	 }
}

